package com.uchengwang.ui.cm_ui.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.LoginConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.cycle.ui.LoadCycleWebHtmlActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.utils.ActivityUtils;
import com.uchengwang.ui.utils.JsonUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.MD5;
import com.uchengwang.ui.utils.NetwotkUtil;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.ShareToWxUtils;
import com.uchengwang.ui.utils.UCommonUtil;


/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AllBaseActivity implements View.OnClickListener{

//    private ActivityTitleBar titleBar;
    private EditText phone, pw;
    private ImageView showPw, wx_login, qq_login, login_sign_image;
    private Button sureBt;
    private TextView lostPw, register;
    private boolean isShow = false;//设置的密码是明文还是隐藏 true 明文
    private String phoneS, pwS;
    private String pwMd5s;
    private boolean isToMain = true;//默认这个界面finish掉时,true切换到主界面
    private LinearLayout login_bm_linear;

//    private MyIUIListener iuiListener;
//    private Tencent tencent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        isToMain = getIntent().getBooleanExtra(BaseConfig.IS_TO_MAIN, true);

//        tencent = Tencent.createInstance("1106230053", getApplicationContext());
//        iuiListener = new MyIUIListener();

        initView();
    }
    
    private void initView (){
//        titleBar = (ActivityTitleBar) findViewById(R.id.login_titleBa);
//        titleBar.setTitle("账户登录", 0);
//        titleBar.setLeftListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                toActivity();
//            }
//        });

        login_sign_image = (ImageView) findViewById(R.id.login_sign_image);

        phone = (EditText) findViewById(R.id.login_phone);
        pw = (EditText) findViewById(R.id.login_pw);
        showPw = (ImageView) findViewById(R.id.login_showPw);
        showPw.setOnClickListener(this);

        sureBt = (Button) findViewById(R.id.login_sureBt);
        sureBt.setOnClickListener(this);

        register = (TextView) findViewById(R.id.login_register);//注册
        register.setOnClickListener(this);
        lostPw = (TextView) findViewById(R.id.login_lostPw);
        lostPw.setOnClickListener(this);

        wx_login = (ImageView) findViewById(R.id.wx_login);//微信登录
        wx_login.setOnClickListener(this);

        login_bm_linear = (LinearLayout) findViewById(R.id.login_bm_linear);
        login_bm_linear.setOnClickListener(this);


        ImageManager.getInstance().loadImage(this, login_sign_image, R.drawable.icon_login_sign, ImageManager.ImageType.NARMOL);

//        qq_login = (ImageView) findViewById(R.id.qq_login);//qq登录
//        qq_login.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        isAutoLogin();
    }

    /**
     * 当本地存有之前的登录信息时,直接登录
     * */
    private void isAutoLogin(){
        phoneS = SPUtils.getPreferences(this).getUserName();
        pwMd5s = SPUtils.getPreferences(this).getAccountPw();

        phone.setText(phoneS);
        if (!TextUtils.isEmpty(pwMd5s)){
            String p = pwMd5s.substring(0, 11);
            pw.setText(p);
        }

        if (!TextUtils.isEmpty(phoneS) && !TextUtils.isEmpty(pwMd5s)){
            login();
        }

    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.wx_login://微信登录
                UCommonUtil.getUtil().showToast(this, "微信登录");
                ShareToWxUtils.getUtils(this).wxLogin();
                break;
//            case R.id.qq_login://qq登录
////                if (iuiListener ==null){
////                    iuiListener = new MyIUIListener();
////                }
////                if (!tencent.isSessionValid()) {
////                    tencent.login(this, "all", new MyIUIListener());
//////                    isServerSideLogin = false;
////                    Log.d("SDKQQAgentPref", "FirstLaunch_SDK:" + SystemClock.elapsedRealtime());
////                }
//
//                break;

            case R.id.login_showPw://显示密码与否
                if (isShow){
                    showPw.setImageResource(R.drawable.hide_pw);
                    pw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pw.setSelection(pw.getText().length());
                    isShow = false;

                }else {
                    showPw.setImageResource(R.drawable.show_pw);
                    pw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pw.setSelection(pw.getText().length());

                    isShow = true;
                }
                break;

            case R.id.login_sureBt://登录
                login();
                break;

            case R.id.login_register://注册
//                intent = new Intent(this, PersonInfoActivity.class);
                intent = new Intent(this, RegisterOrFindPwActivity.class);
                intent.putExtra(BaseConfig.TYPE, 1);
                break;

            case R.id.login_lostPw://忘记密码
                intent = new Intent(this, RegisterOrFindPwActivity.class);
                intent.putExtra(BaseConfig.TYPE, 2);
                break;
            case R.id.login_bm_linear:
                intent = new Intent(this, LoadCycleWebHtmlActivity.class);
                intent.putExtra(BaseConfig.IS_HIDE_RIGHT, true);
                intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/static/agreement.html");
                break;
        }

        if (intent != null){
            startActivity(intent);
        }
    }

    /**
     * 登录
     * */
    private void login(){
        if (!NetwotkUtil.isConnectInternet()){
            UCommonUtil.getUtil().showToast(this, "网络连接不可用");
            return;
        }

        phoneS = phone.getText().toString();//手机号
        if (TextUtils.isEmpty(phoneS)){
            UCommonUtil.getUtil().showToast(this, "请输入登录账号");
            return;
        }
//        if (!phoneS.startsWith("Uni")){
//            if (phoneS.startsWith("uni")){
//                UCommonUtil.getUtil().showToast(this, "Uni账号格式: Uni******");
//                return;
//            }
//
//            if (!CheckUtil.getChecker().checkTelNum(phoneS)){
//                UCommonUtil.getUtil().showToast(this, "手机号码格式不正确");
//                return;
//            }
//        }


        if (TextUtils.isEmpty(pwMd5s)){
            pwS = pw.getText().toString();//密码
            if (TextUtils.isEmpty(pwS)){
                UCommonUtil.getUtil().showToast(this, "请输入密码");
                return;
            }
            if (pwS.length() <6){
                UCommonUtil.getUtil().showToast(this, "密码长度需不少于6位");
                return;
            }
            pwMd5s = MD5.md5(String.valueOf(pwS));
        }



        LoadingUtils.getUtils().loading(this);


        MapRequest map = new MapRequest();
        map.put(BaseConfig.USER_NAME, phoneS);
        map.put(BaseConfig.USER_PWD, pwMd5s);
        map.put(BaseConfig.OPT_SYSTEM, BaseConfig.system);
        map.put(BaseConfig.DEVICE_ID, UCommonUtil.getUtil().getDeviceId(this));
        HttpManager.newInstance(this).query(LoginConfig.Login.method, LoginConfig.Login.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                LoadingUtils.getUtils().hide();
                pwMd5s = "";
                UCommonUtil.getUtil().showToast(LoginActivity.this, msg);
            }

            @Override
            public void onResp(int status, String msg, String data) {
                LoadingUtils.getUtils().hide();
                if (status == 0){
                    if (isToMain){
                        ActivityUtils.getUtils().clearMainActivity();
                    }
                    //登录成功
                    UserBean userBean = JsonUtils.getManager().stringToBean(data, UserBean.class);
                    UChengApplication.TOKEN = userBean.getToken();
                    UChengApplication.nickName = userBean.getNickName();
                    UChengApplication.uniId = userBean.getUniId();
                    UChengApplication.myUniId = userBean.getUniId();
                    UChengApplication.schoolName = userBean.getUniName();
                    UChengApplication.mySchoolName = userBean.getUniName();
                    UChengApplication.uniDataId = userBean.getUniDataId();
                    UChengApplication.sex = userBean.getSex();

                    UChengApplication.userAvatar = userBean.getUserAvatar();
                    UChengApplication.userRole = userBean.getUserRole();
                    UChengApplication.isAuthen = userBean.isAuth();

                    if (UChengApplication.userRole ==BaseConfig.CLUB_ROLE){
                        UChengApplication.clubId = userBean.getId();
                    }else {
                        UChengApplication.uid = userBean.getId();
                    }

                    SPUtils.getPreferences(LoginActivity.this).putInt(BaseConfig.SEX, userBean.getSex());
                    SPUtils.getPreferences(LoginActivity.this).putInt(BaseConfig.USER_ROLE, userBean.getUserRole());
                    SPUtils.getPreferences(LoginActivity.this).setAccountId(userBean.getId());
                    SPUtils.getPreferences(LoginActivity.this).setAccountPw(pwMd5s);
                    SPUtils.getPreferences(LoginActivity.this).setUserName(phoneS);
                    SPUtils.getPreferences(LoginActivity.this).setRealName(userBean.getRealName());
                    SPUtils.getPreferences(LoginActivity.this).putString(BaseConfig.NICK_NAME, userBean.getNickName());
                    SPUtils.getPreferences(LoginActivity.this).putString(BaseConfig.USER_AVATAR, userBean.getUserAvatar());
                    SPUtils.getPreferences(LoginActivity.this).putLong(BaseConfig.UNI_ID, userBean.getUniId());
                    SPUtils.getPreferences(LoginActivity.this).putString(BaseConfig.UNI_NAME, userBean.getUniName());
                    SPUtils.getPreferences(LoginActivity.this).setToken(userBean.getToken());
                    SPUtils.getPreferences(LoginActivity.this).setTokenTime();
                    SPUtils.getPreferences(LoginActivity.this).putBoolean(BaseConfig.IS_AUTHEN, userBean.isAuth());
                    SPUtils.getPreferences(LoginActivity.this).putLong(BaseConfig.UNI_DATA_ID, userBean.getUniDataId());
                    SPUtils.getPreferences(LoginActivity.this).setLinkMainToken(userBean.getToken());
                    SPUtils.getPreferences(LoginActivity.this).putString(BaseConfig.USER_SIGN, userBean.getUserSign());

                    LiteOrmDBUtil.getLiteOrm(LoginActivity.this);

                    toActivity();
                }else {
                    pwMd5s = "";
                    UCommonUtil.getUtil().showToast(LoginActivity.this, msg);
                }
            }
        });
    }

    private void toActivity(){
        if (isToMain){
            Intent intent  = null;
            if (UCommonUtil.getUtil().isLogin() && !TextUtils.isEmpty(UChengApplication.nickName)){
                intent = new Intent(LoginActivity.this, MainActivity.class);
            }else if (UCommonUtil.getUtil().isLogin()){//虽然注册了 但是没有完善用户信息
                intent = new Intent(LoginActivity.this, CompleteInfoActivity.class);
            }else {
                MainActivity.isResumeChange = true;
                intent = new Intent(LoginActivity.this, MainActivity.class);
            }
            if (intent != null){
                startActivity(intent);
            }
        }else {
            MainActivity.isResumeChange = true;
        }

        LoginActivity.this.finish();
        overridePendingTransition(0, R.anim.dd_y_menu_out);
    }

//    @Override
//    public void onBackPressed() {
//        toActivity();
//    }

    /**
     * QQ三方的回调
     * */
//    private class MyIUIListener implements IUiListener{
//
//        @Override
//        public void onComplete(Object o) {
//            Log.d("jjf", "onComplete=");
//            UCommonUtil.getUtil().showToast(LoginActivity.this, "onComplete");
//        }
//
//        @Override
//        public void onError(UiError e) {
//            Log.d("jjf", "onError===code" + e.errorCode + ", msg:" + e.errorMessage + ", detail:" + e.errorDetail);
//            UCommonUtil.getUtil().showToast(LoginActivity.this, "onError");
//        }
//
//        @Override
//        public void onCancel() {
//            Log.d("jjf", "onCancel");
//            UCommonUtil.getUtil().showToast(LoginActivity.this, "onCancel");
//        }
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Tencent.onActivityResultData(requestCode, resultCode, data, new MyIUIListener());
//        if(requestCode == Constants.REQUEST_LOGIN) {
//            if(resultCode == Constants.ACTIVITY_OK) {
//                Tencent.handleResultData(data, iuiListener);
//            }
//        }
    }
}

